package com.dxy.df.core.shiro;


import com.dxy.df.constants.ErrorEnum;
import com.dxy.df.core.exception.BizException;
import com.dxy.df.modules.bean.entity.UserAccountEntity;
import com.dxy.df.modules.bean.query.UserAccountQuery;
import com.dxy.df.modules.service.UserAccountService;
import com.dxy.df.utils.WebUtil;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private UserAccountService userAccountService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof LoginToken;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return new SimpleAuthorizationInfo();
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        String username = WebUtil.getHttpServletRequest().getParameter("username");
        String password = WebUtil.getHttpServletRequest().getParameter("password");
        System.out.println("-----------username:" + username);
        String ticket = (String) token.getPrincipal();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return  null;
        }
        // 用户密码校验
        UserAccountEntity accountEntity =
                userAccountService.queryObject(new UserAccountQuery(username, password));
        if (null != accountEntity) {
            accountEntity.setUserPassword(null);
            return new SimpleAuthenticationInfo(accountEntity, ticket, getName());
        } else {
            return  null;
        }
    }


}
